#include <iostream>
#include <unistd.h>
#include <cassert>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include  <cstring>
using namespace std;
#define MAX 1024

int main()
{
    //第一步，建立管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n == 0);
    (void)n;//防止编译器报警，意料之中用assert,意料之外用if
    cout << "pipefd[0]: " << pipefd[0] << ",pipefd[1]: " << pipefd[1] << endl;
    
    //第二步 创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        perror("fork");
        return 1;
    }

    //子写，父读
    //第三步，父子关闭不需要的fd,形成单向通信的管道
    if(id == 0)
    {
        //child
        close(pipefd[0]);
        //w - 只向管道写入，没有打印
        int cnt = 10;
        while(cnt)
        {
            char message[MAX];
            snprintf(message, sizeof(message), "hello father, I am child, pid: %d, cnt: %d", getpid(), cnt);
            cnt--;
            write(pipefd[1], message, strlen(message));
            sleep(1);
            //cout << "write ..." << endl;

        }
        exit(0);
    }

    //父进程
    close(pipefd[1]);

    //r
    char buffer[MAX];
    while(true)
    {
        sleep(2);
        ssize_t n = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;//'\0'当做字符串
            cout << getpid() << ", " << "child say:" << buffer << "to me!" << endl; 
        }        
    }

    pid_t rid = waitpid(id, nullptr, 0);
    if(rid == id)
    {
        cout << "wait success" << endl;
    }

    return 0;
}
